import * as React from 'react'
import { parse } from 'query-string'
import { Form, Icon, Input, Button, message, Select, AutoComplete, Row, Col } from 'antd';
import _ from 'lodash'
// import EditableTagGroup from 'components/EditableTagGroup';
import AddLanguageTag from 'components/AddLanguageTag'
import { createWordData, getWordData, editWordData, getWordSpell, getPromptData } from 'service/index';
import './index.less'

const FormItem = Form.Item;
const Option = Select.Option;

interface IState {
  kw: string
  isEdit: boolean
  wordInfo: any,
  optionsData: any[],
  isChinesse: string,
  tags: any[],
  text: string,
  showInput: boolean,
  languageType: string,
  tempChinese: string,
  showErrorMessage: boolean
}

class NormalLoginForm extends React.Component<any, IState> {
  constructor(props, context) {
    super(props, context);
    const { type, kw } = parse(this.props.location.search)
    let isChinesse = ''
    if (/[\u4E00-\u9FA5\uF900-\uFA2D]/.test(kw)) {
      isChinesse = 'chinese'
    }
    this.state = {
      isEdit: type === 'edit' ? true : false,
      kw,
      wordInfo: {},
      optionsData: [],
      isChinesse,
      tags: [],
      text: type !== 'edit' && isChinesse !== 'chinese' ? kw : '',
      showInput: type !== 'edit' && isChinesse !== 'chinese' ? true : false,
      languageType:'',
      tempChinese: '',
      showErrorMessage: false
    };
  }
  componentDidCatch(error, info) {
    console.log(error, info);
  }
  componentDidMount() {
    const { isEdit, kw } = this.state
    if (isEdit) {
      // 修改页面获取划词信息
      this.getWordInfo(kw)
    } else if (this.state.isChinesse === 'chinese'){
      // 创建页面获取拼音信息
      this.getPinyin(kw)

    }
  }
  // 获取划词信息
  getWordInfo = (kw) => {
    // let res = {
    //   "result":
    //     {
    //       "id": 1,
    //       "mainId": "1501D",
    //       "subId": "141D",
    //       "intro": "简介",
    //       "chinese":"超声",
    //       "english":"英文",
    //       "japanese":"日文",
    //       "french":"法文",
    //       "german":"德文",
    //       "yongXiang": [{"id":1,"word":"超声"},{"id":2,"word":"成像"}],
    //       "daiXiang": [{"id":1,"word":"超声"},{"id":2,"word":"成像"}],
    //       "shuXiang": [{"id":1,"word":"超声"},{"id":2,"word":"成像"}],
    //       "fenXiang": [{"id":1,"word":"超声"},{"id":2,"word":"成像"}],
    //       "canXiang": [{"id":1,"word":"超声"},{"id":2,"word":"成像"}],
    //       "pinYin": "拼音",
    //       "shortPinyin": "简拼",
    //       "description": "说明",
    //       "creationTime": "时间",
    //       "remark": "备注",
    //     },
    //   "error":null,
    //   "success": true
    // }
    // let tag = []
    // if (res.result) {
    //   const {english , japanese, french, german} = res.result
    //   if (english) {
    //     tag.push({tag: 'english', content: english, id: Number(Math.random().toString().substr(3,10) + Date.now()).toString(36)})
    //   }
    //   if (japanese) {
    //     tag.push({tag: 'japanese', content: japanese, id: Number(Math.random().toString().substr(3,10) + Date.now()).toString(36)})
    //   }
    //   if (french) {
    //     tag.push({tag: 'french', content: french, id: Number(Math.random().toString().substr(3,10) + Date.now()).toString(36)})
    //   }
    //   if (german) {
    //     tag.push({tag: 'german', content: german, id: Number(Math.random().toString().substr(3,10) + Date.now()).toString(36)})
    //   }
    // }
    // this.setState({
    //   wordInfo: res.result,
    //   tags: tag
    // })
    getWordData(kw).then(res => {
      let tag = []
      if (res.result) {
        const {english , japanese, french, german} = res.result
        if (english) {
          tag.push({tag: 'english', content: english, id: Number(Math.random().toString().substr(3,10) + Date.now()).toString(36)})
        }
        if (japanese) {
          tag.push({tag: 'japanese', content: japanese, id: Number(Math.random().toString().substr(3,10) + Date.now()).toString(36)})
        }
        if (french) {
          tag.push({tag: 'french', content: french, id: Number(Math.random().toString().substr(3,10) + Date.now()).toString(36)})
        }
        if (german) {
          tag.push({tag: 'german', content: german, id: Number(Math.random().toString().substr(3,10) + Date.now()).toString(36)})
        }
      }
      this.setState({
        wordInfo: res.result,
        tags: tag
      })
    })
  }

  // 外文获取拼音
  getPinyin = (kw) => {
    // let res = {
    //   "result":
    //     {
    //       "word": "超声成像",
    //     "pinYin": "pinyyin",
    //     "shortPinyin": "jp"
    //     },
    //     "error":null,
    //     "success": true
    //   }
    // const {word, pinYin, shortPinyin} = res.result
    // this.props.form.setFieldsValue({
    //   pinYin, shortPinyin
    // })

    getWordSpell(kw).then(res => {
      if (res.result) {
        const {pinYin, shortPinyin} = res.result
        this.props.form.setFieldsValue({
          pinYin, shortPinyin
        })
      }
    })
  }

  // 获取select焦点
  onFocus = () => {
    this.setState({
      optionsData: []
    })
  }

  // 获取提示信息
  handleSearch = async value => {
    const data = await getPromptData(value)
    // const data = {
    //   "result":
    //   {
    //     words: [
    //       {
    //         "id":1,
    //         "word":"超声成像"
    //       },
    //       {
    //         "id":2,
    //         "word":"超声成形"
    //       },
    //       {
    //         "id":3,
    //         "word":"超声成形很长很长的数据"
    //       },
    //       {
    //         "id":4,
    //         "word":"很长很长的数据测试"
    //       },
    //     ]
    //   },
    //  "error":null,
    // "success": true
    // }
    this.setState({
      optionsData: data.result.words
    })
  }

  // 获取各项选中值
  getValues = arrs => {
     let ids = []
      if (arrs && arrs.length > 0) {
        ids = arrs.map(item => {
          return {id: item.key, word: item.label}
        })
      }
    return ids
  }
  // 提交数据
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (this.state.isChinesse !== 'chinese' && values.tags.length <= 0) {
        this.setState({
          showErrorMessage: true
        })
        message.error('请选择语言类型！')
        return
      }
      if (!err) {
        const { isEdit, wordInfo } = this.state
        let english, japanese, french, german
        values.tags.map(item => {
          switch (item.tag) {
            case 'english':
              english = item.content
              break;
            case 'japanese':
              japanese = item.content
              break;
            case 'french':
              french = item.content
              break;
            case 'german':
              german = item.content
              break;
          }
        })
        if (isEdit) {
          this.editWordData(wordInfo.id, {
            ...values,
            yongXiang: this.getValues(values.yongXiang),
            daiXiang: this.getValues(values.daiXiang),
            shuXiang: this.getValues(values.shuXiang),
            fenXiang: this.getValues(values.fenXiang),
            canXiang: this.getValues(values.canXiang),
            chinese: values.chinese ? values.chinese : this.state.kw,
            english,
            japanese,
            french,
            german
          })
        } else {
          this.createWordData({
            ...values,
            yongXiang: this.getValues(values.yongXiang),
            daiXiang: this.getValues(values.daiXiang),
            shuXiang: this.getValues(values.shuXiang),
            fenXiang: this.getValues(values.fenXiang),
            canXiang: this.getValues(values.canXiang),
            chinese: values.chinese ? values.chinese : this.state.kw,
            english,
            japanese,
            french,
            german
          })
        }
      }
    });
  }

  // 关闭窗口
  closeWindow = () => {
    this.props.history.push('/word')
    try {
      dotNetMessage.closewindow()
    } catch (error) {

    }
  }
  // 创建
  createWordData = async values => {
    const data = await createWordData(values)
    if (data.result) {
      message.success('创建成功', this.closeWindow)
    }
  }

  // 编辑
  editWordData = async (id, values) => {
    const data = await editWordData(id, values)
    if (data.result) {
      message.success('编辑成功', this.closeWindow)
    }
  }
  // 取消
  handleCancle = () => {
    this.closeWindow()
  }

   // 各个项数据处理
   getLabelValue = arrs => {
    let ids = []
     if (arrs && arrs.length > 0) {
       ids = arrs.map(item => {
         return {key: item.id, label: item.word}
       })
     }
   return ids
 }

  //修改中文
  changeChinese = value => {
    this.setState({
      tempChinese: value
    })
  }
  render() {
    const { wordInfo = {}, isEdit, kw, optionsData, isChinesse, tags, showInput } = this.state
    let { yongXiang = [], daiXiang = [], shuXiang = [], fenXiang = [], canXiang =[],
      chinese, mainId, pinYin, shortPinyin, description, intro } = wordInfo
      yongXiang = this.getLabelValue(yongXiang)
      daiXiang = this.getLabelValue(daiXiang)
      shuXiang = this.getLabelValue(shuXiang)
      fenXiang = this.getLabelValue(fenXiang)
      canXiang = this.getLabelValue(canXiang)
    const { getFieldDecorator } = this.props.form;
    const formItemLayout1 = {
      labelCol: {
        xs: { span: 6 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 19 },
        sm: { span: 19 },
      },
    };
    const formItemLayout2 = {
      labelCol: {
        xs: { span: 4 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 20 },
        sm: { span: 20 },
      },
    };

    const options = optionsData.map(item => <Option key={item.id} >{item.word}</Option>)
    const dataSource = optionsData.map(item => item.word)
    return (
      <Form onSubmit={this.handleSubmit} className="page-handle-word word-edit">
        <div className="triangle">
          <div className="logo"><img src="assets/images/logo.png" alt=""/></div>
        </div>
        <div className="title-input" title={kw}>{kw}</div>
        <div className="input-container">
        <Row className="tow-colum">
          {isChinesse !== 'chinese' && <Col span={12}>
            <FormItem
              {...formItemLayout1}
              label="中文"
            >
              {getFieldDecorator('chinese', {
                initialValue: chinese,
                rules: [{ required: true, message: '请输入中文', whitespace: true}]
              })(
                <AutoComplete
                  dataSource={dataSource}
                  onFocus = {this.onFocus}
                  onBlur={() => this.getPinyin(this.state.tempChinese)}
                  onChange={value => this.changeChinese(value)}
                  onSearch={this.handleSearch}
                  placeholder="请输入中文"
                />
              )}
            </FormItem>
          </Col>}
          <Col span={12}>
            <FormItem
              {...formItemLayout1}
              label="拼音"
            >
              {getFieldDecorator('pinYin', {
                initialValue: pinYin,
                // rules: [{ required: true, message: 'Please input your nickname!', whitespace: true }]
              })(
                <Input />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row className="tow-colum">
          <Col span={12}>
            <FormItem
              {...formItemLayout1}
              label="简拼"
            >
              {getFieldDecorator('shortPinyin', {
                initialValue: shortPinyin,
                // rules: [{ required: true, message: 'Please input your nickname!', whitespace: true }]
              })(
                <Input />
              )}
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem
              {...formItemLayout1}
              label="主范畴"
            >
              {getFieldDecorator('mainId', {
                initialValue: mainId,
                // rules: [{ required: true, message: 'Please input your nickname!', whitespace: true }]
              })(
                <Input />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row className="one-colum">
          <Col span={24}>
            <FormItem
              {...formItemLayout2}
              label="语言"
            >
              {getFieldDecorator('tags', {
                initialValue: tags,
                // rules: [{required: true, message: '请填写语言' }]
              })(
                <AddLanguageTag wordInfo={wordInfo} showInput={showInput} text={this.state.text} showErrorMessage={this.state.showErrorMessage}/>
              )}
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem
              {...formItemLayout2}
              label="说明"
            >
              {getFieldDecorator('description', {
                initialValue: description
              })(
                <Input maxLength={500}/>
              )}
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem
              {...formItemLayout2}
              label="用项"
            >
              {getFieldDecorator('yongXiang', {
                initialValue: yongXiang,
              })(
                <Select
                  mode="multiple"
                  labelInValue
                  size="small"
                  placeholder="请输入并选择"
                  notFoundContent='无匹配结果'
                  filterOption={false}
                  onFocus={this.onFocus}
                  onSearch={this.handleSearch}
                  style={{ width: '100%' }}
                >
                  {options}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem
              {...formItemLayout2}
              label="代项"
            >
              {getFieldDecorator('daiXiang', {
                initialValue: daiXiang
              })(
                <Select
                  mode="multiple"
                  labelInValue
                  size="small"
                  placeholder="请输入并选择"
                  notFoundContent='无匹配结果'
                  filterOption={false}
                  onFocus={this.onFocus}
                  onSearch={this.handleSearch}
                  style={{ width: '100%' }}
                >
                  {options}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem
              {...formItemLayout2}
              label="属项"
            >
              {getFieldDecorator('shuXiang', {
                initialValue: shuXiang
              })(
                <Select
                  mode="multiple"
                  labelInValue
                  size="small"
                  placeholder="请输入并选择"
                  notFoundContent='无匹配结果'
                  filterOption={false}
                  onFocus={this.onFocus}
                  onSearch={this.handleSearch}
                  style={{ width: '100%' }}
                >
                  {options}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem
              {...formItemLayout2}
              label="分项"
            >
              {getFieldDecorator('fenXiang', {
                initialValue: fenXiang
              })(
                <Select
                  mode="multiple"
                  labelInValue
                  size="small"
                  placeholder="请输入并选择"
                  notFoundContent='无匹配结果'
                  filterOption={false}
                  onFocus={this.onFocus}
                  onSearch={this.handleSearch}
                  style={{ width: '100%' }}
                >
                  {options}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem
              {...formItemLayout2}
              label="参项"
            >
              {getFieldDecorator('canXiang', {
                initialValue: canXiang
              })(
                <Select
                  mode="multiple"
                  labelInValue
                  size="small"
                  placeholder="请输入并选择"
                  notFoundContent='无匹配结果'
                  filterOption={false}
                  onFocus={this.onFocus}
                  onSearch={this.handleSearch}
                  style={{ width: '100%' }}
                >
                  {options}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem
              {...formItemLayout2}
              label="简介"
            >
              {getFieldDecorator('intro', {
                initialValue: intro
              })(
                <Input.TextArea placeholder="请输入简介" maxLength={500}/>
              )}
            </FormItem>
          </Col>
        </Row>
        </div>
        <div className="footer container">
          <Button type="primary" htmlType="submit">提交</Button>
          <Button onClick={this.handleCancle}>取消</Button>
        </div>
      </Form>
    );
  }
}

const WordConstructor = Form.create()(NormalLoginForm);

export default WordConstructor
